<?php
/**
 * @Author: Zhaojun(13040@qq.com)
 * @Date:   2018-03-26 16:40:16
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2021-03-23 16:58:04
 */

namespace app\actstar\controller;

require_once CMF_ROOT."extend/weixin_pay/lib/WxPay.Api.php";
require_once CMF_ROOT."extend/weixin_pay/lib/WxPay.Notify.php";

class Wxpay extends ActstarBase {

	function initialize() {
		parent::initialize();

		$weixinAccountDao = model('weixin_manage/WeixinAccount');
		$weixinAccountInfo = $weixinAccountDao->getInfo(2); //昆山全知道

		//支付账号初始化
		define('WXDB_APPID', $weixinAccountInfo['appid']);
		define('WXDB_MCHID', $weixinAccountInfo['mchid']);
		define('WXDB_MCHKEY', $weixinAccountInfo['mchkey']);
		define('WXDB_APPSECRET', $weixinAccountInfo['appsecret']);
		define('WXDB_SSLCERT_PATH', EXTEND_PATH.'weixin/'.$weixinAccountInfo['wxnumber'].'/apiclient_cert.pem');
		define('WXDB_SSLKEY_PATH', EXTEND_PATH.'weixin/'.$weixinAccountInfo['wxnumber'].'/apiclient_key.pem');

		$this->signupDao = model('actstar_manage/Signup');
	}

	public function doJsapiTest() {
		$this->display("Pinche:wx_jsapi");
	}

	public function doJsapi() {
		$signupId = input('param.signupId', '', 'intval');
		if (!$signupId) {
			$this->wapError('报名ID有误');
		}

		//获取报名记录信息
		$signupInfo = $this->signupDao->getInfo($signupId);
		if (empty($signupInfo)) {
			$this->wapError('非法订单');
		}
		if (!$signupInfo['total_fee']) {
			$this->wapError('订单金额非法');
		}

		//=========准备
		$totalFee = $signupInfo['total_fee'];
		$orderNo = $signupInfo['order_no'];
		$subject = '支付活动订单'.$totalFee.'元';

		$this->assign('signupInfo', $signupInfo);
		$this->assign('totalFee', $totalFee);

		$totalFee = intval($totalFee * 100);

		//支付返回地址
		$returnUrl = "http://".$_SERVER['HTTP_HOST']."/actstar/mySignup/detail/signupId/".$signupId;
		$this->assign('returnUrl', $returnUrl);

		//调试
		//$this->display("pay_wx_jsapi");

		//=========微信支付开始
		ini_set('date.timezone','Asia/Shanghai');
		require_once EXTEND_PATH."weixin_pay/example/WxPay.JsApiPay.php";

		//①、获取用户openid
		$tools = new \JsApiPay();
		//$openid = $tools->GetOpenid(); //即时获取用户的openid
		$openid = $this->moondb['openid'];
		if (!$openid) {
			$this->wapError('openId获取失败');
		}

		//更新支付的openid
// 		$data = [
// 			'pay_openid' => $openid,
// 		];
// 		$this->signupDao->baseUpdateData($signupId, $data);

		//②、统一下单
		$input = new \WxPayUnifiedOrder();
		$input->SetBody($subject);
		$input->SetAttach($signupId);
		$input->SetOut_trade_no($orderNo);
		//$input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));
		$input->SetTotal_fee($totalFee);
		//$input->SetTime_start(date("YmdHis"));
		//$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag($subject);
		$input->SetNotify_url("http://".$_SERVER['HTTP_HOST']."/actstar/wxpay/doNotify");
		$input->SetTrade_type("JSAPI");
		$input->SetOpenid($openid);
		$order = \WxPayApi::unifiedOrder($input);
		//print_r($order);exit;

		$jsApiParameters = $tools->GetJsApiParameters($order);
		$this->assign('jsApiParameters', $jsApiParameters);

		//$editAddress = $tools->GetEditAddressParameters();
		//$this->assign('editAddress', $editAddress);

		return $this->fetch('pay_wx_jsapi');
	}

	//http://www2.ekunshan.cn/piece/pincheWxpay/doNativeTest
	public function doNativeTest() {
		$this->display("Pinche:wx_native");
	}

	//http://www2.ekunshan.cn/piece/pincheWxpay/doNative
	public function doNative() {
		$signupId = I('get.signupId', 0, 'pwEscape');
		if (!$signupId) {
			$this->wapError('订单号有误');
		}

		//获取报名记录信息
		$signupInfo = $this->signupDao->getInfo($signupId);

		//=========准备
		$signupId = $signupInfo['id'];
		$totalFee = $signupInfo['total_fee'];
		$orderNo = $signupInfo['order_no'];
		$subject = '用户'.$signupInfo['username'].'支付活动订单'.$totalFee.'元';

		$this->assign('signupInfo', $signupInfo);
		$this->assign('totalFee', $totalFee);

		//====准备
		$totalFee = intval($totalFee * 100);

		require_once APP_PATH."Common/Lib/weixinPayHd/example/WxPay.NativePay.php";

		//模式一
		/**
		 * 流程：
		 * 1、组装包含支付信息的url，生成二维码
		 * 2、用户扫描二维码，进行支付
		 * 3、确定支付之后，微信服务器会回调预先配置的回调地址，在【微信开放平台-微信支付-支付配置】中进行配置
		 * 4、在接到回调通知之后，用户进行统一下单支付，并返回支付信息以完成支付（见：native_notify.php）
		 * 5、支付完成之后，微信服务器会通知支付成功
		 * 6、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
		 */
		$notify = new \NativePay();

		//模式二
		/**
		 * 流程：
		 * 1、调用统一下单，取得code_url，生成二维码
		 * 2、用户扫描二维码，进行支付
		 * 3、支付完成之后，微信服务器会通知支付成功
		 * 4、在支付成功通知中需要查单确认是否真正支付成功（见：notify.php）
		 */
		$input = new \WxPayUnifiedOrder();
		$input->SetBody($subject);
		$input->SetAttach($signupId);
		$input->SetOut_trade_no($orderNo);
		$input->SetTotal_fee($totalFee);
		$input->SetTime_start(date("YmdHis"));
		//$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag($subject);
		$input->SetNotify_url('http://'.$_SERVER['HTTP_HOST'].'/bcmall/productWxpay/doNotify');
		$input->SetTrade_type("NATIVE");
		$input->SetProduct_id("123456789");

		$result = $notify->GetPayUrl($input);

		if ($result['return_code'] == FAIL) {
			//$msg = iconv('utf-8', 'gbk', $result['err_code_des'].'('.$result['err_code'].')');
			$msg = $result['return_msg'];
			$this->wapError($msg);
		} else if ($result['result_code'] == FAIL) {
			$msg = $result['err_code_des'];
			$this->wapError($msg);
		} else {
			$url = $result["code_url"];
			$this->assign('url', $url);
			$this->display("pay_wx_native");
		}
	}

	//http://www2.ekunshan.cn/wap/weggWxpay/doNotify
	public function doNotify() {
		$notify = new PayNotifyCallBack();
		$notify->Handle(false);
	}
}

class PayNotifyCallBack extends \WxPayNotify {

	public function Queryorder($transaction_id) {
		$input = new \WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = \WxPayApi::orderQuery($input);
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}

	public function NotifyProcess($paymentData, &$msg) {
		if(!array_key_exists("transaction_id", $paymentData)){
			$msg = "输入参数不正确";
			return false;
		}

		//查询订单，判断订单真实性
		if(!$this->Queryorder($paymentData["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}

		$parameter = array(
			"out_trade_no"   => $paymentData['out_trade_no'],      //商户订单编号；
			"trade_no"       => $paymentData['transaction_id'],          //支付宝交易号；
			"total_fee"      => $paymentData['total_fee'],         //交易金额；
			"trade_status"   => $paymentData['result_code'],      //交易状态
			"notify_id"      => $paymentData['transaction_id'],         //通知校验ID。
			"notify_time"    => $paymentData['time_end'],       //通知的发送时间。
			"buyer_email"    => $paymentData['openid'],       //买家支付宝帐号
		);
		db('Aaaa')->insert(['space'=>'actstar', 'module'=>'wxpay', 'flag'=>'NotifyProcess', 'content'=>pw_var_export($parameter)]);

		require_once(APP_PATH.'actstar/orderFunction.php');
		_orderHandle($parameter, 'wxpay', 0);

		return true;
	}

}